package training.双指针


fun main() {


    println(checkInclusion("ab", "eidbaooo"))
}


fun checkInclusion(s1: String, s2: String): Boolean {

    val dic = Array<Int>(256) { i -> 0 }

    var chars = 0 //记录有多少个独立的字符

    for (c in s1) {
        if (dic[c.toInt()] == 0) chars++
        dic[c.toInt()]++
    }

    //对 s2 双指针运算

    var i = 0
    var j = s1.length

    //s2 双指针，从 i -> j 对字符计数 ，如果和 dic 一样，那么满足条件
    //中间如果出现 s1 中没有出现的字符，直接 从 i+1 重新开始

    var encounter = 0

    var encounterDic = Array<Int>(256) { 0 }

    while (i <= j && i < s2.length && j < s2.length) {

        val ch = s2[i]

        //遇到一个不存在的字符
        if (dic[ch.toInt()] == 0) {
            j = i + s1.length

            //清空
            for (k in encounterDic.indices)
                encounterDic[k] = 0
            continue
        }


        if (encounterDic[ch.toInt()] == 0)
            encounter++

        encounterDic[ch.toInt()]++


        i++

    }


    return encounter == chars

}